/*
 * Copyright Thoughtworks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// utils
import { docsUrl } from "gen/gocd_version";
import { queryParamAsString } from "helpers/url";
import _ from "lodash";
import m from "mithril";
import Stream from "mithril/stream";
import { Scms } from "models/materials/pluggable_scm";
import { PluggableScmCRUD } from "models/materials/pluggable_scm_crud";
import { PackagesCRUD } from "models/package_repositories/packages_crud";
import { PackageRepositories, Packages } from "models/package_repositories/package_repositories";
import { PackageRepositoriesCRUD } from "models/package_repositories/package_repositories_crud";
import { ExtensionTypeString } from "models/shared/plugin_infos_new/extension_type";
import { PluginInfos } from "models/shared/plugin_infos_new/plugin_info";
import { PluginInfoCRUD } from "models/shared/plugin_infos_new/plugin_info_crud";
// components
import { ConceptDiagram } from "views/components/concept_diagram";
import { i18n } from "helpers/i18n";
import { EnvironmentVariablesWidget } from "views/components/environment_variables";
import { Link } from "views/components/link";
import { Page, PageState } from "views/pages/page";
import { PipelineActions } from "views/pages/pipelines/actions";
import { AdvancedSettings } from "views/pages/pipelines/advanced_settings";
import { FillableSection } from "views/pages/pipelines/fillable_section";
import { JobEditor } from "views/pages/pipelines/job_editor";
import { MaterialEditor } from "views/pages/pipelines/material_editor";
// models
import { PipelineConfigVM } from "views/pages/pipelines/pipeline_config_view_model";
import { PipelineInfoEditor } from "views/pages/pipelines/pipeline_info_editor";
import { StageEditor } from "views/pages/pipelines/stage_editor";
import { TaskTerminalField } from "views/pages/pipelines/task_editor";
import { UserInputPane } from "views/pages/pipelines/user_input_pane";
import { PackageRepositoriesPage } from "./package_repositories";

const materialImg = require("../../../app/assets/images/concept_diagrams/concept_material.svg");
const pipelineImg = require("../../../app/assets/images/concept_diagrams/concept_pipeline.svg");
const stageImg = require("../../../app/assets/images/concept_diagrams/concept_stage.svg");
const jobImg = require("../../../app/assets/images/concept_diagrams/concept_job.svg");

interface State {
  pluginInfos: Stream<PluginInfos>;
  packageRepositories: Stream<PackageRepositories>;
  packages: Stream<Packages>;
  scmMaterials: Stream<Scms>;
}

export class PipelineCreatePage extends Page<{}, State> {
  private model = new PipelineConfigVM();

  pageName(): string {
    return i18n.tSyncForPage("admin.add_pipeline.page.title", "admin-pipelines");
  }

  oninit(vnode: m.Vnode<{}, State>) {
    super.oninit(vnode);
    const group = queryParamAsString(window.location.search, "group").trim();

    if ("" !== group) {
      this.model.pipeline.group(group);
    }

    // 添加详细的 debug 信息
    console.log("=== PIPELINES PAGE DEBUG INFO ===");
    console.log("Current URL:", window.location.href);
    console.log("Current pathname:", window.location.pathname);
    console.log("Current search:", window.location.search);
    console.log("Setting current page context to: admin-pipelines");

    // 设置当前页面上下文为 admin-pipelines
    i18n.setCurrentPage("admin-pipelines");

    // 检查 i18n 服务状态
    console.log("i18n service status:", i18n.getCacheStatus());
    console.log("Current i18n page context: admin-pipelines (manually set)");

    // 预加载 admin-pipelines 翻译
    console.log("Loading admin-pipelines translations...");
    i18n
      .loadPageTranslations("admin-pipelines")
      .then(() => {
        console.log("✅ Successfully loaded admin-pipelines translations");
        console.log("Updated i18n service status:", i18n.getCacheStatus());

        // 检查是否还有其他页面在加载
        const cacheStatus = i18n.getCacheStatus();
        if (cacheStatus.loadingPages.length > 0) {
          console.warn("⚠️ Other pages still loading:", cacheStatus.loadingPages);
        }

        // 检查是否有 admin-templates 相关的翻译被加载
        if (cacheStatus.cachedPages.includes("admin-templates")) {
          console.warn("⚠️ admin-templates translations are cached, this might cause issues");
        }
      })
      .catch((error) => {
        console.error("❌ Failed to load admin-pipelines translations:", error);
        console.error("Error details:", {
          message: error.message,
          stack: error.stack,
          name: error.name,
        });
      });

    // 检查是否有其他组件可能在使用 admin-templates 翻译
    console.log("Checking for potential admin-templates usage...");
    setTimeout(() => {
      const cacheStatus = i18n.getCacheStatus();
      console.log("Delayed i18n status check:", cacheStatus);

      if (cacheStatus.cachedPages.includes("admin-templates")) {
        console.warn("🚨 admin-templates translations detected in cache!");
        console.warn("This suggests some component is still using admin-templates keys");
      }
    }, 1000);

    vnode.state.pluginInfos = Stream(new PluginInfos());
    vnode.state.packageRepositories = Stream();
    vnode.state.packages = Stream();
    vnode.state.scmMaterials = Stream();
  }

  componentToDisplay(vnode: m.Vnode<{}, State>): m.Children {
    const { pipeline, material, stage, job, isUsingTemplate } = this.model;
    const mergedPkgRepos = PackageRepositoriesPage.getMergedList(vnode.state.packageRepositories, vnode.state.packages);

    // 添加翻译键使用监控
    console.log("=== RENDERING PIPELINES PAGE ===");
    console.log("Using translation keys for admin-pipelines page");

    // 检查 i18n 缓存状态
    const cacheStatus = i18n.getCacheStatus();
    console.log("Current i18n cache status:", cacheStatus);

    if (cacheStatus.cachedPages.includes("admin-templates")) {
      console.warn("🚨 WARNING: admin-templates translations are cached!");
      console.warn("This might cause the admin.templates.editor.use.template warning");
    }

    return [
      <FillableSection>
        <UserInputPane heading={i18n.tSyncForPage("admin.add_pipeline.part1.title", "admin-pipelines")}>
          <MaterialEditor
            material={material}
            showExtraMaterials={true}
            pluggableScms={vnode.state.scmMaterials()}
            pipelineGroupName={this.model.pipeline.group()}
            readonly={false}
            packageRepositories={mergedPkgRepos}
            pluginInfos={vnode.state.pluginInfos()}
          />
        </UserInputPane>
        <ConceptDiagram image={materialImg}>
          <span
            dangerouslySetInnerHTML={{
              __html: i18n.tSyncForPage("pipelines.concept.material.description", "admin-pipelines"),
            }}
          />
        </ConceptDiagram>
      </FillableSection>,

      <FillableSection>
        <UserInputPane heading={i18n.tSyncForPage("admin.add_pipeline.part2.title", "admin-pipelines")}>
          <PipelineInfoEditor pipelineConfig={pipeline} isUsingTemplate={isUsingTemplate} />
        </UserInputPane>
        <ConceptDiagram image={pipelineImg}>
          <span
            dangerouslySetInnerHTML={{
              __html: i18n.tSyncForPage("pipelines.concept.pipeline.description", "admin-pipelines"),
            }}
          />
        </ConceptDiagram>
      </FillableSection>,

      this.model.whenTemplateAbsent(() => [
        <FillableSection>
          <UserInputPane heading={i18n.tSyncForPage("admin.add_pipeline.part3.title", "admin-pipelines")}>
            <StageEditor stage={stage} />
          </UserInputPane>
          <ConceptDiagram image={stageImg}>
            <span
              dangerouslySetInnerHTML={{
                __html: i18n.tSyncForPage("pipelines.concept.stage.description", "admin-pipelines"),
              }}
            />
          </ConceptDiagram>
        </FillableSection>,

        <FillableSection>
          <UserInputPane heading={i18n.tSyncForPage("admin.add_pipeline.part4.title", "admin-pipelines")}>
            <JobEditor job={job} />
            <TaskTerminalField
              label={i18n.tSyncForPage("pipelines.task.terminal.label", "admin-pipelines")}
              property={job.tasks}
              errorText={job.errors().errorsForDisplay("tasks")}
              required={true}
            />
            <AdvancedSettings forceOpen={_.some(job.environmentVariables(), (env) => env.errors().hasErrors())}>
              <EnvironmentVariablesWidget environmentVariables={job.environmentVariables()} />
            </AdvancedSettings>
          </UserInputPane>
          <ConceptDiagram image={jobImg}>
            <span
              dangerouslySetInnerHTML={{
                __html: i18n.tSyncForPage("pipelines.concept.job.description", "admin-pipelines"),
              }}
            />
          </ConceptDiagram>
        </FillableSection>,
      ]),

      <PipelineActions pipelineConfig={pipeline} />,
    ];
  }

  fetchData(vnode: m.Vnode<{}, State>): Promise<any> {
    console.log("=== FETCHING PIPELINES DATA ===");
    console.log("Starting data fetch for pipelines page");

    return Promise.all([
      PluginInfoCRUD.all({ type: ExtensionTypeString.PACKAGE_REPO }),
      PluginInfoCRUD.all({ type: ExtensionTypeString.SCM }),
      PackageRepositoriesCRUD.all(),
      PackagesCRUD.all(),
      PluggableScmCRUD.all(),
    ])
      .then((result) => {
        console.log("✅ All data fetched successfully");

        // 检查数据加载后的翻译状态
        const cacheStatus = i18n.getCacheStatus();
        console.log("i18n cache status after data fetch:", cacheStatus);

        if (cacheStatus.cachedPages.includes("admin-templates")) {
          console.warn("🚨 admin-templates translations loaded during data fetch!");
          console.warn("This suggests some component or service is loading admin-templates");
        }

        [result[0], result[1]].forEach((apiResult) =>
          apiResult.do((successResponse) => {
            vnode.state.pluginInfos().push(...successResponse.body);
            this.pageState = PageState.OK;
          }, this.setErrorState)
        );

        result[2].do((successResponse) => {
          vnode.state.packageRepositories(successResponse.body);
          this.pageState = PageState.OK;
        }, this.setErrorState);

        result[3].do((successResponse) => {
          vnode.state.packages(successResponse.body);
          this.pageState = PageState.OK;
        }, this.setErrorState);

        result[4].do((successResponse) => {
          vnode.state.scmMaterials(successResponse.body);
          this.pageState = PageState.OK;
        }, this.setErrorState);
      })
      .catch((error) => {
        console.error("❌ Error during data fetch:", error);
        console.error("Error details:", {
          message: error.message,
          stack: error.stack,
          name: error.name,
        });
      });
  }

  helpText(): m.Children {
    console.log("=== RENDERING HELP TEXT ===");
    console.log("Rendering help text for pipelines page");

    // 检查当前的翻译状态
    const cacheStatus = i18n.getCacheStatus();
    console.log("i18n cache status in helpText:", cacheStatus);

    if (cacheStatus.cachedPages.includes("admin-templates")) {
      console.warn("🚨 admin-templates translations detected in helpText!");
      console.warn("This might be the source of the warning");
    }

    return (
      <div>
        {i18n.tSyncForPage("pipelines.help.text", "admin-pipelines")}&nbsp;
        <Link href={docsUrl("configuration/quick_pipeline_setup.html")} target="_blank" externalLinkIcon={true}>
          {i18n.tSyncForPage("pipelines.help.link.text", "admin-pipelines")}
        </Link>
      </div>
    );
  }
}

// 添加全局错误监听和翻译监控
console.log("=== PIPELINES PAGE MODULE LOADED ===");

// 监听全局错误
window.addEventListener("error", (event) => {
  if (event.message && event.message.includes("admin.templates")) {
    console.error("🚨 GLOBAL ERROR with admin.templates:", event);
    console.error("Error details:", {
      message: event.message,
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno,
      error: event.error,
    });
  }
});

// 监听未处理的 Promise 拒绝
window.addEventListener("unhandledrejection", (event) => {
  if (event.reason && event.reason.message && event.reason.message.includes("admin.templates")) {
    console.error("🚨 UNHANDLED PROMISE REJECTION with admin.templates:", event.reason);
    console.error("Promise rejection details:", {
      message: event.reason.message,
      stack: event.reason.stack,
      name: event.reason.name,
    });
  }
});

// 定期检查翻译状态
setInterval(() => {
  try {
    const cacheStatus = i18n.getCacheStatus();
    if (cacheStatus.cachedPages.includes("admin-templates")) {
      console.warn("🚨 PERIODIC CHECK: admin-templates translations still in cache!");
      console.warn("Cache status:", cacheStatus);
    }
  } catch (error) {
    console.error("Error in periodic translation check:", error);
  }
}, 5000); // 每5秒检查一次
